package com.zqs.takeredpackage.job;


import cn.dev33.satoken.stp.StpUtil;
import com.zqs.takeredpackage.entity.RedPackage;
import com.zqs.takeredpackage.util.RedPackageStoreUtil;
import com.zqs.takeredpackage.util.UserStoreUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

/**
 * 红包定时任务
 */
@Component
public class RedPackageJob {

    private static final UserStoreUtil userStoreUtil = new UserStoreUtil();
    private static final long RED_PACKAGE_EXPIRE_TIME = 24 * 60 * 60 * 1000; // 1天毫秒数
    /**
     * 清理时间超过1天的红包,若红包还有金额，则退回用户
     */
    @Scheduled(cron = "15 * * * * ?")
    public void clearRedPackage() {
        System.out.println("清理时间超过1天的红包");
        Iterator<RedPackage> iterator = RedPackageStoreUtil.userRedPackage.values().iterator();
        int count = 0;
        while (iterator.hasNext()) {
            RedPackage redPackage = iterator.next();
            String userId = redPackage.getUserId();

            // 红包金额为0
            if (BigDecimal.ZERO.compareTo(redPackage.getRemainMoney()) == 0) {
                Map<String, ArrayList<String>> userRedPackageKeys = RedPackageStoreUtil.userRedPackageKeys;
                if (userRedPackageKeys.containsKey(userId)) {
                    userRedPackageKeys.get(userId).remove(redPackage.getId());
                }
                iterator.remove(); // 安全移除当前红包
                continue;
            }

            // 判断红包是否过期（创建时间 + 1天 < 当前时间）
            Date createTime = redPackage.getCreateTime();
            if (createTime == null) {
                continue; // 忽略无创建时间的红包
            }
            long expireTime = createTime.getTime() + RED_PACKAGE_EXPIRE_TIME;
            if (expireTime < System.currentTimeMillis()) {
                // 如果还有余额，退回用户
                if (redPackage.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                    userStoreUtil.updateUserRedPackage(
                            userStoreUtil.getUserById(userId).getAccount(),
                            redPackage.getRemainMoney()
                    );
                }

                // 删除红包信息
                Map<String, ArrayList<String>> userRedPackageKeys = RedPackageStoreUtil.userRedPackageKeys;
                if (userRedPackageKeys.containsKey(userId)) {
                    userRedPackageKeys.get(userId).remove(redPackage.getId());
                }
                iterator.remove(); // 安全移除当前红包
            }
            count++;
        }

        System.out.println("清理结束---" +  count);
    }
}
